package com.msconfig.mvp.view.fragment;

/*
 * author: caojunhao
 * date  : 2020/6/17
 * desc  :
 */

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.geo.msconfig.R;
import com.msconfig.MyApplication;
import com.msconfig.bean.ConfigInfoBean;
import com.msconfig.device.CommandSendManage;
import com.msconfig.device.DeviceManage;
import com.msconfig.device.GetSendCommandList;
import com.msconfig.device.TagSendCommand;
import com.msconfig.event.RenameDetermineEvent;
import com.msconfig.io.RtkResponseDataListener;
import com.msconfig.mvp.view.activity.base.BaseMvpActivity;
import com.msconfig.mvp.view.activity.base.BaseMvpFragment;
import com.msconfig.mvp.view.activity.base.BasePresenter;
import com.msconfig.mvp.view.adapter.ConfigAdapter;
import com.msconfig.utils.DataCacheUtils;
import com.msconfig.utils.WriteToFileUtils;
import com.msconfig.widget.MyListView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import static android.view.View.VISIBLE;
import static com.msconfig.mvp.view.fragment.SaveConfigFragment.CONFIGFILE;

public class ApplyConfigFragment extends BaseMvpFragment implements View.OnClickListener {
    private FrameLayout flLoading;
    private ImageView ivLoading;
    private Animation setupAnim;
    private ImageView ivCommonBack;
    private TextView tvCommonTitle;
    private MyListView listview;
    private ConfigAdapter adapter;
    private HashSet<ConfigInfoBean> hashSet;
    private Button btnAllChoose;
    private Button btnAllNochoose;
    private Button btnDel;
    private Button btnRename;
    private Button btnApply;
    private Button btnCancal;
    private Button btnDetail;
    private LinearLayout llDel;
    private LinearLayout llApply;
    private RenameConfigFragment renameConfigFragment;
    public ConfigInfoBean bean;



    private ArrayList<ConfigInfoBean> configInfoBeans;


    private Context context;
    private Activity activity;
    public static final String FILENAME="filename";
    protected static final int MSG_SAVE_SUCC =1;
    protected static final int MSG_SAVE_DEFAIL =2;
    private MyHandler myHandler;
    private boolean isSaveOk;//是否保存成功

    private static class MyHandler extends Handler {
        WeakReference<ApplyConfigFragment> weakReference;

        private MyHandler(ApplyConfigFragment fragment) {
            weakReference = new WeakReference<ApplyConfigFragment>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            ApplyConfigFragment fragment = weakReference.get();
            if (fragment != null) {
                switch (msg.what) {
                    case MSG_SAVE_SUCC:
                        fragment.applySucc();
                        break;
                    case MSG_SAVE_DEFAIL:
                        if(!fragment.isSaveOk){
                            DeviceManage.getInstance().RegRtkRespondDataListener(null);
                            fragment.stopAnim();
                            Toast.makeText(fragment.context,"配置失败！",Toast.LENGTH_SHORT).show();
                        }
                        break;
                }
            }
        }
    }

    private void applySucc() {
        isSaveOk=true;
        stopAnim();
        DeviceManage.getInstance().RegRtkRespondDataListener(null);
        //重新获取最新数据
        ArrayList<TagSendCommand> sendCommandList = GetSendCommandList.getGetAllCommandList();
        //设置发送命令额集合
        CommandSendManage.getInstance().setSendCommandList(sendCommandList);
        //开始发送命令
        CommandSendManage.getInstance().startSendCommand();
        Toast.makeText(context,"配置成功！",Toast.LENGTH_SHORT).show();
        backTo();
    }


    public static ApplyConfigFragment newInstance() {
        Bundle args = new Bundle();
        ApplyConfigFragment fragment = new ApplyConfigFragment();
        fragment.setArguments(args);
        return fragment;
    }

    //当Activity与fragment建立关联时调用
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context=context;
        activity= (Activity) context;
    }

    @Override
    public void onClick(View v) {
        if(v==ivCommonBack){
            backTo();
        }else if ( v == btnAllChoose ) {
            onClickAllChoose();
        } else if ( v == btnAllNochoose ) {
            onClickNoAllChoose();
        } else if ( v == btnDel ) {
            onClickDel();
        } else if ( v == btnRename ) {
            onClickRename();
        } else if ( v == btnApply ) {
            onClickApply();
        }else if ( v == btnDetail ) {
            onClickDetail();
        }else if ( v == btnCancal ) {
            onClickCancal();
        }
    }


    @Override
    protected void createPresenter(List<BasePresenter> mPresenters) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.layout_fragment_apply_config;
    }

    @Override
    protected void initView(View view) {
        ivCommonBack=view.findViewById(R.id.iv_common_back);
        tvCommonTitle=view.findViewById(R.id.tv_common_title);

        listview = (MyListView)view.findViewById( R.id.myListview);
        btnAllChoose = (Button)view.findViewById( R.id.btn_all_choose );
        btnAllNochoose = (Button)view.findViewById( R.id.btn_all_nochoose );
        btnDel = (Button)view.findViewById( R.id.btn_del );
        btnRename = (Button)view.findViewById( R.id.btn_rename );
        btnApply = (Button)view.findViewById( R.id.btn_apply );
        btnCancal = (Button)view.findViewById( R.id.btn_cancel );
        btnDetail = (Button)view.findViewById( R.id.btn_details );
        llDel = (LinearLayout) view.findViewById( R.id.ll_del );
        llApply = (LinearLayout) view.findViewById( R.id.ll_apply );

        flLoading=view.findViewById(R.id.fl_loading);
        ivLoading = view.findViewById(R.id.iv_loading);

    }

    @Override
    protected void initListener(View view) {
        ivCommonBack.setOnClickListener(this);
        btnAllChoose.setOnClickListener( this );
        btnAllNochoose.setOnClickListener( this );
        btnDel.setOnClickListener( this );
        btnRename.setOnClickListener( this );
        btnApply.setOnClickListener( this );
        btnCancal.setOnClickListener( this );
        btnDetail.setOnClickListener( this );
    }

    @Override
    protected void initData() {
        tvCommonTitle.setText(R.string.title_apply_config);
        myHandler =new MyHandler(this);
        configInfoBeans= DataCacheUtils.loadListCache(context, CONFIGFILE);
        adapter=new ConfigAdapter(context,configInfoBeans);
        listview.setAdapter(adapter);
        hashSet=new HashSet<>();
        listview.setAdapter(adapter);
        if(configInfoBeans.size()==0){
            btnRename.setClickable(false);
            btnDetail.setClickable(false);
            btnApply.setClickable(false);
        }
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                RelativeLayout rl=view.findViewById(R.id.parent);
                CheckBox checkBox=(CheckBox) view.findViewById(R.id.checkbox);
                if(checkBox.getVisibility()==View.GONE){//针对单选，也就是没有复选框的情况
                    listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
                    bean= (ConfigInfoBean) parent.getItemAtPosition(position);
                    adapter.setCurrentItem(position);
                    adapter.setmIsClick(true);
                    adapter.notifyDataSetChanged();
                } else{//复选框可见时，代表可以多选
                    if(hashSet.add(configInfoBeans.get(position))){
                        checkBox.setChecked(true);
                    }else{
                        hashSet.remove(configInfoBeans.get(position));
                        checkBox.setChecked(false);
                    }
                }

            }
        });

        listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                //显示复选框，删除等按钮
                llDel.setVisibility(View.VISIBLE);
                llApply.setVisibility(View.GONE);
                adapter.flage=true;
                adapter.notifyDataSetChanged();
                return false;
            }
        });
    }


    private void onClickAllChoose() {

        for (int i = 0; i < configInfoBeans.size(); i++) {
            configInfoBeans.get(i).isCheck = true;
            //添加进这个hashset集合
            hashSet.add(configInfoBeans.get(i));
        }
        adapter.notifyDataSetChanged();
        btnAllChoose.setVisibility(View.GONE);
        btnAllNochoose.setVisibility(View.VISIBLE);
    }

    private void onClickNoAllChoose() {
        for (int i = 0; i < configInfoBeans.size(); i++) {
            configInfoBeans.get(i).isCheck = false;
            //添加进这个hashset集合
            hashSet.remove(configInfoBeans.get(i));
        }
        adapter.notifyDataSetChanged();

        btnAllChoose.setVisibility(View.VISIBLE);
        btnAllNochoose.setVisibility(View.GONE);
    }

    private void onClickCancal() {
        llDel.setVisibility(View.GONE);
        llApply.setVisibility(View.VISIBLE);
        adapter.flage= false;
        adapter.notifyDataSetChanged();
    }

    private void onClickDel() {
        //1.根据文件名删除文件
        Iterator<ConfigInfoBean> it = hashSet.iterator();
        while(it.hasNext()){
            ConfigInfoBean configInfoBean=it.next();
            WriteToFileUtils.deleteFile(configInfoBean.getFileName());
            configInfoBeans.remove(configInfoBean);
        }
        //移除缓存的configInfoBeans
        DataCacheUtils.saveListCache(context, configInfoBeans, CONFIGFILE);
        adapter.notifyDataSetChanged();

    }

    private void onClickRename() {
        if(bean==null){//选中的item
            Toast.makeText(context,"请选择一个文件！",Toast.LENGTH_SHORT).show();
            return;
        }
        Bundle bundle=new Bundle();
        bundle.putString(FILENAME,bean.getFileName());
        renameConfigFragment = RenameConfigFragment.newInstance(bundle);
        if(!renameConfigFragment.isAdded()){
            renameConfigFragment.setCancelable(false);
            renameConfigFragment.show(activity.getFragmentManager(), "rename");
        }
    }


    //重命名之后回来
    //修改缓存数据
    //修改文件名称
    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void getRenameFilename(RenameDetermineEvent event) {
        WriteToFileUtils.renameFile(bean.getFileName(),event.getFileName()+".txt");
        int index = configInfoBeans.indexOf(bean);
        configInfoBeans.get(index).setFileName(event.getFileName()+".txt");
        DataCacheUtils.saveListCache(context, configInfoBeans, CONFIGFILE);
        adapter.notifyDataSetChanged();
    }

    private void onClickDetail() {
        if(bean==null){//选中的item
            Toast.makeText(context,"请选择需要查看的配置文件！",Toast.LENGTH_SHORT).show();
            return;
        }
        Bundle bundle=new Bundle();
        bundle.putString(FILENAME,bean.getFileName());
        ((BaseMvpActivity)activity).goToNextFragment(this, ConfigFileDetailFragment.newInstance(bundle));
    }

    private void onClickApply() {
        if(bean==null){//选中的item
            Toast.makeText(context,"请选择一个文件！",Toast.LENGTH_SHORT).show();
            return;
        }
        isSaveOk=false;
        startAnim();
        myHandler.sendEmptyMessageDelayed(MSG_SAVE_DEFAIL,8000);
        new Thread(){
            @Override
            public void run() {
                startApplyConfig(bean.getFileName());
            }
        }.start();
    }

    public void startApplyConfig(String fileName){
        String filePath= Environment.getExternalStorageDirectory()+"/"+fileName;
        File file =new File(filePath);
        if (!file.isFile() && !file.exists()) {
            return ;
        }
        InputStreamReader inputReader = null;
        BufferedReader buffreader = null;
        InputStream instream=null;
        try {
            instream = new FileInputStream(file);
            inputReader= new InputStreamReader(instream);
            buffreader = new BufferedReader(inputReader);
            String line;
            StringBuilder stringBuilder;
            //分行读取
            while (( line = buffreader.readLine()) != null) {
                if (DeviceManage.getInstance().isConnected()) {

                    //去掉一些不必要设置的数据
                    //设备信息
                    if(line.startsWith("@GNSS,GET,DEVICE.INFO") ||
                            line.startsWith("@GNSS,GET,DEVICE.POWER_LEVEL") ||
                            line.startsWith("@GNSS,GET,DEVICE.EXT_VOLTAGE") ||
                            line.startsWith("@GNSS,GET,DEVICE.DISK.SPACE") ||
                            line.startsWith("@GNSS,GET,DEVICE.WIFI.SIGNAL_LEVEL"))
                    continue;

                    if(line.startsWith("@GNSS,GETALL")){//发送这个命令的目的是为了判断设置完成否
                        DeviceManage.getInstance().sendCommand("SET,@GNSS,GETALL\r\n");
                        break;
                    }

                    String[] sField ;
                    String value = "";
                    sField = line.split(",");

                    if (sField.length == 4) {//@GNSS,GET,DEVICE.INFO.SERIAL,OK,
                        value = "";
                    } else if (sField.length == 5) {//@GNSS,GET,DEVICE.INFO.SERIAL,OK,M32018010013
                        value = sField[sField.length - 1];
                    }

                    stringBuilder=new StringBuilder();
                    stringBuilder.append("SET,");
                    stringBuilder.append(sField[2]);
                    stringBuilder.append(",");
                    stringBuilder.append(value);
                    DeviceManage.getInstance().sendCommand(stringBuilder+"\r\n");

                    RtkResponseDataListener rtkResponseDataListener=new RtkResponseDataListener() {
                        @Override
                        //@GNSS,SET,GETALL,ERROR,2
                        public void OnRtkResponseCallBack(String strGnssLine) {
                            //表示结束
                            if(strGnssLine.startsWith("@GNSS,SET,@GNSS,GETALL")){
                                myHandler.sendEmptyMessage(MSG_SAVE_SUCC);
                            }
                        }
                    };

                    //注册Rtk回复数据监听
                    DeviceManage.getInstance().RegRtkRespondDataListener(rtkResponseDataListener);

                }else{
                    return;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(inputReader!=null){
                    inputReader.close();
                }
                if(buffreader!=null){
                    buffreader.close();
                }
                if(instream!=null){
                    instream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //开始动画
    public void startAnim(){
        setupAnim = AnimationUtils.loadAnimation(context, R.anim.anim_round_rotate);
        LinearInterpolator interpolator = new LinearInterpolator();  //设置匀速旋转，在xml文件中设置会出现卡顿
        setupAnim.setInterpolator(interpolator);
        if (setupAnim != null) {
            flLoading.setVisibility(VISIBLE);
            ivLoading.startAnimation(setupAnim);  //开始动画
        }
    }

    //停止动画
    private void stopAnim() {
        if (setupAnim != null) {
            setupAnim=null;
            flLoading.setVisibility(View.GONE);
            ivLoading.clearAnimation();
        }
    }


}
